package com.tekj.cxqcb.view.Module.activity.Order;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.tekj.cxqcb.R;
import com.tekj.cxqcb.operation.BusinessDao;
import com.tekj.cxqcb.operation.resultBean.PubStatusBean;
import com.tekj.cxqcb.operation.resultBean.UploadFiles;
import com.tekj.cxqcb.view.Module.activity.Order.CarOrderDetailsActivity;
import com.tekj.cxqcb.view.Module.adapter.Proposal2Adapter;
import com.tekj.cxqcb.view.Module.bean.ImageBean;
import com.tekj.cxqcb.view.Module.bean.UpdateRequestContractBean;
import com.tekj.cxqcb.view.Module.decoration.SpacesItemDecoration;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import common.base.activity.BaseActivity;
import common.base.operationHelper.Bean.BindingViewBean;
import common.tool.Tools;
import common.widget.ZoomImageView;
import es.dmoral.toasty.Toasty;

import static com.tekj.cxqcb.view.Module.activity.Order.CarOrderDetailsActivity.orderData;
import static com.tekj.cxqcb.view.Module.activity.Order.ContractInformationActivity.getLocalMedias;
import static com.tekj.cxqcb.view.Module.activity.Order.NewOrdersTwoActivity.ImgString;

/**
 * 请款信息
 */
public class RequestInformationActivity extends BaseActivity {
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_l)
    TextView tvL;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_r)
    ImageView ivR;
    @BindView(R.id.tv_r)
    TextView tvR;
    @BindView(R.id.ll_right)
    LinearLayout llRight;
    @BindView(R.id.rl_title_bg)
    RelativeLayout rlTitleBg;
    @BindView(R.id.tv_sl1)
    TextView tvSl1;
    @BindView(R.id.rv_rchy)
    RecyclerView rvRchy;
    @BindView(R.id.tv_sl2)
    TextView tvSl2;
    @BindView(R.id.rv_syx)
    RecyclerView rvSyx;
    @BindView(R.id.tv_sl3)
    TextView tvSl3;
    @BindView(R.id.rv_mqqrh)
    RecyclerView rvMqqrh;
    @BindView(R.id.tv_sl4)
    TextView tvSl4;
    @BindView(R.id.rv_mqqrhhy)
    RecyclerView rvMqqrhhy;
    @BindView(R.id.tv_sl5)
    TextView tvSl5;
    @BindView(R.id.rv_fp)
    RecyclerView rvFp;
    @BindView(R.id.tv_sl6)
    TextView tvSl6;
    @BindView(R.id.rv_jqx)
    RecyclerView rvJqx;
    @BindView(R.id.tv_sl7)
    TextView tvSl7;
    @BindView(R.id.rv_swbzq)
    RecyclerView rvSwbzq;
    @BindView(R.id.rv_qtzl)
    RecyclerView rvQtzl;
    @BindView(R.id.tv_submission)
    TextView tvSubmission;


    private BusinessDao businessDao;

    private Proposal2Adapter adapter, adapter2, adapter3,
            adapter4, adapter5, adapter6,
            adapter7, adapter8;

    private List<LocalMedia> localMedias, localMedias2, localMedias3,
            localMedias4, localMedias5, localMedias6,
            localMedias7, localMedias8;

    private List<ImageBean> imgs1, imgs2, imgs3,
            imgs4, imgs5, imgs6,
            imgs7, imgs8;
    UpdateRequestContractBean requestContractBean;

    private String urls[] = {
            "https://apk.cars-cxqc.com/%E4%BA%BA%E8%BD%A6%E5%90%88%E5%BD%B1.jpg",
            "https://apk.cars-cxqc.com/%E5%95%86%E4%B8%9A%E4%BF%9D%E9%99%A9.jpg",
            "https://apk.cars-cxqc.com/%E9%9D%A2%E7%AD%BE%E7%A1%AE%E8%AE%A4%E5%87%BD.jpg",
            "https://apk.cars-cxqc.com/%E7%A1%AE%E8%AE%A4%E5%87%BD%E5%90%88%E5%BD%B1.jpg",
            "https://apk.cars-cxqc.com/%E5%8F%91%E7%A5%A8.jpg",
            "https://apk.cars-cxqc.com/%E4%BA%A4%E5%BC%BA%E9%99%A9.jpg",
            "https://apk.cars-cxqc.com/%E7%A1%AE%E8%AE%A4%E5%87%BD%E6%8F%A1%E7%AC%94%E7%AD%BE%E5%90%8D%E7%85%A7.jpg"
    };

    @Override
    public void init() {
        tvTitle.setText("请款信息");
        businessDao = new BusinessDao(activity, activity);
        requestContractBean = new UpdateRequestContractBean();
        requestContractBean.setOrderId(CarOrderDetailsActivity.orderData.getDetail().getId());
        initList();
    }

    @Override
    public int setLayout() {
        return R.layout.activity_request_information;
    }

    @Override
    public void initLoadStart() {
        showDialog();
    }

    @Override
    public void initLoadEnd() {
        dialog.dismiss();
    }

    @Override
    public void initBindingView(Object mBean) {
        BindingViewBean bindingViewBean = (BindingViewBean) mBean;
        switch (bindingViewBean.getmEnumStatus()) {
            case 多文件上传:
                UploadFiles uploadFiles = (UploadFiles) bindingViewBean.getBean();
                if (!uploadFiles.getCode().equals("0000000")) {
                    Toasty.normal(activity, uploadFiles.getMsg()).show();
                    return;
                }
                if (uploadFiles.getTypeName().equals("人车合影")) {
                    addImg(uploadFiles, imgs1);
                } else if (uploadFiles.getTypeName().equals("商业险")) {
                    addImg(uploadFiles, imgs2);
                } else if (uploadFiles.getTypeName().equals("面签确认函")) {
                    addImg(uploadFiles, imgs3);
                } else if (uploadFiles.getTypeName().equals("面签确认函合影")) {
                    addImg(uploadFiles, imgs4);
                } else if (uploadFiles.getTypeName().equals("发票")) {
                    addImg(uploadFiles, imgs5);
                } else if (uploadFiles.getTypeName().equals("交强险")) {
                    addImg(uploadFiles, imgs6);
                } else if (uploadFiles.getTypeName().equals("手握笔坐签")) {
                    addImg(uploadFiles, imgs7);
                } else if (uploadFiles.getTypeName().equals("其他资料")) {
                    addImg(uploadFiles, imgs8);
                }
                break;

            case 请款信息上传:

                PubStatusBean pubStatusBean = (PubStatusBean) bindingViewBean.getBean();
                if (pubStatusBean.getCode().equals("0000000")) {
                    finish();
                }
                Toasty.normal(activity, pubStatusBean.getMsg()).show();
                break;
        }

    }

    @OnClick({R.id.ll_back, R.id.tv_sl1, R.id.tv_sl2, R.id.tv_sl3,
            R.id.tv_sl4, R.id.tv_sl5, R.id.tv_sl6, R.id.tv_sl7,
            R.id.tv_submission})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.tv_sl1:
                showPop(urls[0]);
                break;
            case R.id.tv_sl2:
                showPop(urls[1]);
                break;
            case R.id.tv_sl3:
                showPop(urls[2]);
                break;
            case R.id.tv_sl4:
                showPop(urls[3]);
                break;
            case R.id.tv_sl5:
                showPop(urls[4]);
                break;
            case R.id.tv_sl6:
                showPop(urls[5]);
                break;
            case R.id.tv_sl7:
                showPop(urls[6]);
                break;
            case R.id.tv_submission:
                if (orderData.getOrder().getOrderStatus() != 8) {
                    Toasty.normal(activity, "请款信息未审核或已通过").show();
                    return;
                }
                if (imgs1.size() == 0 || imgs2.size() == 0 || imgs3.size() == 0 ||
                        imgs4.size() == 0 || imgs5.size() == 0 || imgs6.size() == 0 ||
                        imgs7.size() == 0) {
                    Toasty.normal(activity, "请先上传所需图片").show();
                    return;
                }
                requestContractBean.setRchy(ImgString(imgs1));
                requestContractBean.setSyx(ImgString(imgs2));
                requestContractBean.setMqqrh(ImgString(imgs3));
                requestContractBean.setMqqrhhy(ImgString(imgs4));
                requestContractBean.setInvoice(ImgString(imgs5));
                requestContractBean.setJqx(ImgString(imgs6));
                requestContractBean.setSwbzq(ImgString(imgs7));
                requestContractBean.setQtzlzp(ImgString(imgs8));
                Tools.showNormalDialogOne(activity, "提交信息", "是否提交？", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        businessDao.UpdateRequestContract(requestContractBean);
                    }
                }, null);

                break;
        }
    }

    /**
     * 初始化List，adapter
     */
    public void initList() {
        localMedias = new ArrayList<>();
        localMedias2 = new ArrayList<>();
        localMedias3 = new ArrayList<>();
        localMedias4 = new ArrayList<>();
        localMedias5 = new ArrayList<>();
        localMedias6 = new ArrayList<>();
        localMedias7 = new ArrayList<>();
        localMedias8 = new ArrayList<>();

        imgs1 = new ArrayList<>();
        imgs2 = new ArrayList<>();
        imgs3 = new ArrayList<>();
        imgs4 = new ArrayList<>();
        imgs5 = new ArrayList<>();
        imgs6 = new ArrayList<>();
        imgs7 = new ArrayList<>();
        imgs8 = new ArrayList<>();

        if (CarOrderDetailsActivity.orderData.getDetail().getRchy() != null) {
            getImges(CarOrderDetailsActivity.orderData.getDetail().getRchy(), imgs1, localMedias);
        }
        if (CarOrderDetailsActivity.orderData.getDetail().getSyx() != null) {
            getImges(CarOrderDetailsActivity.orderData.getDetail().getSyx(), imgs2, localMedias2);
        }
        if (CarOrderDetailsActivity.orderData.getDetail().getMqqrh() != null) {
            getImges(CarOrderDetailsActivity.orderData.getDetail().getMqqrh(), imgs3, localMedias3);
        }

        if (CarOrderDetailsActivity.orderData.getDetail().getMqqrhhy() != null) {
            getImges(CarOrderDetailsActivity.orderData.getDetail().getMqqrhhy(), imgs4, localMedias4);
        }
        if (CarOrderDetailsActivity.orderData.getDetail().getInvoice() != null) {
            getImges(CarOrderDetailsActivity.orderData.getDetail().getInvoice(), imgs5, localMedias5);
        }
        if (CarOrderDetailsActivity.orderData.getDetail().getJqx() != null) {
            getImges(CarOrderDetailsActivity.orderData.getDetail().getJqx(), imgs6, localMedias6);
        }
        if (CarOrderDetailsActivity.orderData.getDetail().getSwbzq() != null) {
            getImges(CarOrderDetailsActivity.orderData.getDetail().getSwbzq(), imgs7, localMedias7);
        }
        if (CarOrderDetailsActivity.orderData.getDetail().getQtzlzp() != null) {
            getImges(CarOrderDetailsActivity.orderData.getDetail().getQtzlzp(), imgs8, localMedias8);
        }

        adapter = new Proposal2Adapter(activity, localMedias, isModify());
        adapter2 = new Proposal2Adapter(activity, localMedias2, isModify());
        adapter3 = new Proposal2Adapter(activity, localMedias3, isModify());
        adapter4 = new Proposal2Adapter(activity, localMedias4, isModify());
        adapter5 = new Proposal2Adapter(activity, localMedias5, isModify());
        adapter6 = new Proposal2Adapter(activity, localMedias6, isModify());
        adapter7 = new Proposal2Adapter(activity, localMedias7,isModify());
        adapter8 = new Proposal2Adapter(activity, localMedias8, isModify());

        initAdaper(adapter, localMedias, rvRchy, imgs1, 1001);
        initAdaper(adapter2, localMedias2, rvSyx, imgs2, 1002);
        initAdaper(adapter3, localMedias3, rvMqqrh, imgs3, 1003);
        initAdaper(adapter4, localMedias4, rvMqqrhhy, imgs4, 1004);
        initAdaper(adapter5, localMedias5, rvFp, imgs5, 1005);
        initAdaper(adapter6, localMedias6, rvJqx, imgs6, 1006);
        initAdaper(adapter7, localMedias7, rvSwbzq, imgs7, 1007);
        initAdaper(adapter8, localMedias8, rvQtzl, imgs8, 1008);
    }

    public void initAdaper(final Proposal2Adapter adapter, final List<LocalMedia> localMedias,
                           RecyclerView recyclerView, final List<ImageBean> imgs, final int code) {


        adapter.setOnCallbackListener(new Proposal2Adapter.OnCallbackListener() {
            @Override
            public void onAddPhotoClick() {
                //添加图片
                Tools.InitPictureSelector(activity, false, code,
                        getLocalMedias(localMedias), 9 - localMedias.size());
            }

            @Override
            public void onPicturePreview(int position) {
                //图片预览
//                PictureSelector.create(activity).externalPicturePreview(position, localMedias);
            }

            @Override
            public void onPictureDelete(int position) {
                localMedias.remove(position);
                imgs.remove(position);
                adapter.setList(localMedias, localMedias.size() + 1);
            }
        });

        recyclerView.setLayoutManager(new GridLayoutManager(activity, 3));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new SpacesItemDecoration(10));
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> lists;
        List<File> list = new ArrayList<>();
        if (resultCode == RESULT_OK) {
            lists = PictureSelector.obtainMultipleResult(data);
            switch (requestCode) {
                case 1001:
                    upImg(lists, list, localMedias, adapter, "人车合影");
                    break;
                case 1002:
                    upImg(lists, list, localMedias2, adapter2, "商业险");
                    break;
                case 1003:
                    upImg(lists, list, localMedias3, adapter3, "面签确认函");
                    break;
                case 1004:
                    upImg(lists, list, localMedias4, adapter4, "面签确认函合影");
                    break;
                case 1005:
                    upImg(lists, list, localMedias5, adapter5, "发票");
                    break;
                case 1006:
                    upImg(lists, list, localMedias6, adapter6, "交强险");
                    break;
                case 1007:
                    upImg(lists, list, localMedias7, adapter7, "手握笔坐签");
                    break;
                case 1008:
                    upImg(lists, list, localMedias8, adapter8, "其他资料");
                    break;
            }
        }
    }

    /**
     * @param uploadFiles
     * @param imgs
     */
    void addImg(UploadFiles uploadFiles, List<ImageBean> imgs) {
        if (imgs == null) {
            return;
        }
        String[] files = uploadFiles.getData().getUploadFilePath().split(",");
        Iterator it = imgs.iterator();
        while (it.hasNext()) {
            ImageBean m = (ImageBean) it.next();
            if (!m.isInitial()) {
                it.remove();
            }
        }
        for (int i = 0; i < files.length; i++) {
            imgs.add(new ImageBean(files[i], false));
        }
    }

    /**
     * 添加图片
     *
     * @param data
     */
    void addLocalMedias(List<LocalMedia> data, List<LocalMedia> localMedias) {
        boolean isadd;
        for (int i = 0; i < data.size(); i++) {
            isadd = true;
            for (int j = 0; j < localMedias.size(); j++) {
                if (localMedias.get(j).getCompressPath().equals(data.get(i).getCompressPath())) {
                    isadd = false;
                }
            }
            if (isadd)
                localMedias.add(data.get(i));
        }

    }

    /**
     * 记录上传的地址
     *
     * @param lists
     * @param list
     * @param localMedias
     * @param adapter
     * @param typename
     */
    void upImg(List<LocalMedia> lists, List<File> list,
               List<LocalMedia> localMedias, Proposal2Adapter adapter,
               String typename) {
        for (int i = 0; i < lists.size(); i++) {
            if (lists.get(i) != null && !lists.get(i).getCompressPath().equals("")) {
                list.add(new File(lists.get(i).getCompressPath()));
            }
        }
        businessDao.uploadFiles(list, typename);
        addLocalMedias(lists, localMedias);
        adapter.setList(localMedias, localMedias.size() < 9 ? localMedias.size() + 1 : 9);
    }

    void getImges(String imgString, List<ImageBean> imgs, List<LocalMedia> localMedias) {
        if (imgString.equals("")) {
            return;
        }
        String[] strings = imgString.split(",");
        for (int i = 0; i < strings.length; i++) {
            imgs.add(new ImageBean(strings[i], true));
            LocalMedia media = new LocalMedia();
            media.setCompressed(true);
            media.setCompressPath(strings[i]);
            localMedias.add(media);
        }
    }

    private PopupWindow popupWindow;
    private View popupView;
    private TranslateAnimation animation;

    /**
     * 提示图片
     *
     * @param url
     */
    private void showPop(String url) {
        Tools.lightoff(activity);
        popupView = View.inflate(activity, R.layout.pop_help_img, null);
        popupWindow = new PopupWindow(popupView, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);


        animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, 0,
                Animation.RELATIVE_TO_PARENT, -1, Animation.RELATIVE_TO_PARENT, 0);
        animation.setInterpolator(new AccelerateInterpolator());
        animation.setDuration(200);

        LinearLayout linearLayout = popupView.findViewById(R.id.ll_back);
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        ZoomImageView imageView = popupView.findViewById(R.id.img_help);
        Tools.picassoNetwork(url, imageView);

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                Tools.lighton(activity);
            }
        });

        popupWindow.showAtLocation(tvTitle, Gravity.CENTER, 0, 0);
        popupView.startAnimation(animation);

    }

    public static boolean isModify() {
        if (orderData.getOrder().getOrderStatus() != 8) {
            return false;
        }
        return true;
    }
}
